﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Specialized;

public sealed class HttpModule
{
    public static byte[] RequestSelfToPOST(string url, byte[] buffer)
    {
        return RequestSelfToPOST(url, buffer, buffer.Length);
    }

    public static byte[] RequestSelfToPOST(string url, byte[] buffer, int size)
    {
        try
        {
            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Proxy = null;
            request.Method = "POST";
            request.KeepAlive = false;
            request.ContentLength = size;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Timeout = 10000;
            Stream stream = request.GetRequestStream();
            stream.Write(buffer, 0, size);
            stream.Flush();
            stream.Close();
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            System.IO.Stream responseStream = response.GetResponseStream();
            try
            {
                List<byte> bytes = new List<byte>();
                int b;
                while ((b = responseStream.ReadByte()) != -1)
                {
                    bytes.Add((byte)b);
                }
                return bytes.ToArray();
            }
            finally
            {
                if (responseStream != null)
                    responseStream.Close();
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    public static string RequestSelfToGETString(string url, string chertCode)
    {
        try
        {
            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.KeepAlive = false;
            request.Timeout = 10000;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            System.IO.Stream responseStream = response.GetResponseStream();
            try
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding(chertCode));
                return reader.ReadToEnd();
            }
            finally
            {
                if (responseStream != null)
                    responseStream.Close();
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    public static string RequestSelfToGETString(string url)
    {
        try
        {
            return RequestSelfToGETString(url, "GBK");
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}